/*
 * Project Name spring-boot-tools
 * File Name MessageHandler
 * Package Name com.huxiaosu.tools.cmpp.service
 * Create Time 2024/4/18
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.action;

import com.huxiaosu.tools.cmpp.action.MessageActionPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.huxiaosu.tools.cmpp.model.BaseMessage;

/**
 * Description
 *
 * @author liujie
 * @date 2024/4/18 23:47
 */
@Slf4j
public class MessageHandler extends IoHandlerAdapter {

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("<sessionCreated()...sessionId= {} >", session.getId());
        }
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("<sessionOpened()...sessionId= {} >", session.getId());
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("<sessionClosed()...sessionId= {} >", session.getId());
        }
        session.closeNow();

    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("<sessionIdle()...sessionId= {} >", session.getId());
        }
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("<sessionIdle()...sessionId= {} sentMsg ={}>", session.getId(),
                    ToStringBuilder.reflectionToString(message));
        }
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("<exceptionCaught()... {}>", cause.getMessage());
        }
        cause.printStackTrace();
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        log.debug("messageReceived()...业务消息处理" + ToStringBuilder.reflectionToString(message));
        // 业务消息处理
        BaseMessage baseMessage = (BaseMessage) message;
        MessageActionPool.getInstance().getAction(baseMessage.getCommandId()).executeAction(session, baseMessage);
    }

}
